package com.example.demo.controller;

import com.example.demo.dao.ArticleRepository;
import com.example.demo.model.Article;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import xyz.erupt.annotation.fun.PowerObject;
import xyz.erupt.annotation.sub_field.Edit;
import xyz.erupt.annotation.sub_field.EditType;
import xyz.erupt.annotation.sub_field.sub_edit.AttachmentType;
import xyz.erupt.core.annotation.EruptRouter;
import xyz.erupt.core.constant.EruptConst;
import xyz.erupt.core.controller.EruptModifyController;
import xyz.erupt.core.i18n.I18nTranslate;
import xyz.erupt.core.invoke.DataProcessorManager;
import xyz.erupt.core.invoke.DataProxyInvoke;
import xyz.erupt.core.prop.EruptProp;
import xyz.erupt.core.service.EruptCoreService;
import xyz.erupt.core.service.EruptService;
import xyz.erupt.core.util.DateUtil;
import xyz.erupt.core.util.EruptUtil;
import xyz.erupt.core.util.Erupts;
import xyz.erupt.core.view.EruptApiModel;
import xyz.erupt.core.view.EruptModel;
import xyz.erupt.jpa.dao.EruptDao;
import xyz.erupt.upms.annotation.EruptLoginAuth;
import xyz.erupt.upms.annotation.EruptMenuAuth;
import xyz.erupt.upms.model.EruptUser;
import xyz.erupt.upms.model.log.EruptLoginLog;
import xyz.erupt.upms.service.EruptUserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@RestController
public class TestController {

    @Autowired
    private ArticleRepository articleRepository;

    @Resource
    private EruptDao eruptDao;

    //获取文章列表
    @RequestMapping("/test")
    public List<Article> testArticle() {
        // Erupt jdbc方式调用
        return eruptDao.queryEntityList(Article.class);
        // JPA jdbc方式调用
        //  return articleRepository.findAll();
    }

//    @Autowired
//    private RestTemplate restTemplate;
    @Autowired
    private HttpServletRequest request;

    @SneakyThrows
    @RequestMapping("/newMenu")
    public EruptApiModel uploadExcel() {
        // 设置用户信息,拿到当前登录用户并且设置全局token

        // 定义模板
        // 导入结构文件excel，进行解析
        // 调用接口，生成对应配置
        // 获取java源文件，并复制到指定目录
        // 重启应用
        // 表格内容建议手动
        // 录入，excel只定义结构[在系统中录入数据，减少工作流程]
        JsonObject data = new Gson().fromJson("{\n" +
                "    \"name\": \"a8\",\n" +
                "    \"status\": \"1\",\n" +
                "    \"parentMenu\": {\n" +
                "        \"id\": \"168\",\n" +
                "        \"name\": \"8888\"\n" +
                "    },\n" +
                "    \"sort\": 172\n" +
                "}", JsonObject.class);
        EruptModel eruptModel = EruptCoreService.getErupt("EruptMenu");
        Erupts.powerLegal(eruptModel, PowerObject::isAdd);
        Map<String, Object> extraData = new HashMap<>();
        EruptApiModel eruptApiModel = EruptUtil.validateEruptValue(eruptModel, data);
        if (eruptApiModel.getStatus() == EruptApiModel.Status.ERROR) return eruptApiModel;
        Object obj = EruptUtil.jsonToEruptEntity(eruptModel, data, extraData);
        DataProxyInvoke.invoke(eruptModel, (dataProxy -> dataProxy.beforeAdd(obj)));
        DataProcessorManager.getEruptDataProcessor(eruptModel.getClazz()).addData(eruptModel, obj);
        this.modifyLog(eruptModel, "ADD", data.toString());
        DataProxyInvoke.invoke(eruptModel, (dataProxy -> dataProxy.afterAdd(obj)));
        return EruptApiModel.successApi();
    }

    private void modifyLog(EruptModel eruptModel, String placeholder, String content) {
        log.info("[" + eruptModel.getEruptName() + " -> " + placeholder + "]:" + content);
    }

    @Autowired
    private EruptProp eruptProp;

    private static final String FS_SEP = "/";

    // TODO 定义上传excel页面以及解析excel创建目录以及表格
    @SneakyThrows
    @PostMapping("/upload/{erupt}/{field}")
    @EruptRouter(authIndex = 2, verifyType = EruptRouter.VerifyType.ERUPT)
    public EruptApiModel importExcel(@PathVariable("erupt") String eruptName, @PathVariable("field") String fieldName, @RequestParam("file") MultipartFile file) {
        EruptModel eruptModel = EruptCoreService.getErupt(eruptName);
        Erupts.powerLegal(eruptModel, powerObject -> powerObject.isEdit() || powerObject.isAdd());
        Edit edit = eruptModel.getEruptFieldMap().get(fieldName).getEruptField().edit();
        String path;
        if (eruptProp.isKeepUploadFileName()) {
            path = File.separator + DateUtil.getFormatDate(new Date(), DateUtil.DATE) + File.separator + file.getOriginalFilename()
                    .replaceAll("&|#|\\?|\\s", "").replace(edit.attachmentType().fileSeparator(), "");
        } else {
            String[] fileNameSplit = file.getOriginalFilename().split("\\.");
            path = File.separator + DateUtil.getFormatDate(new Date(), DateUtil.DATE)
                    + File.separator + RandomStringUtils.randomAlphabetic(12) + EruptConst.DOT + fileNameSplit[fileNameSplit.length - 1];
        }
        if (edit.type() == EditType.ATTACHMENT) {
            // 附件
            if (edit.attachmentType().type() == AttachmentType.Type.IMAGE) {
                // TODO 默认上传excel，解析excel
                return EruptApiModel.successApi(path.replace("\\", "/"));
            }
        }
        return EruptApiModel.errorApi(I18nTranslate.$translate("erupt.upload_error") + " ");
    }

}